/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import pojos.Customer;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.PreexistingEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pojos.Bill;
import java.util.ArrayList;
import java.util.Collection;
import javax.transaction.UserTransaction;

/**
 *
 * @author A7med Kotb
 */
public class CustomerJpaController implements Serializable {

    public CustomerJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Customer customer) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (customer.getBillCollection() == null) {
            customer.setBillCollection(new ArrayList<Bill>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<Bill> attachedBillCollection = new ArrayList<Bill>();
            for (Bill billCollectionBillToAttach : customer.getBillCollection()) {
                billCollectionBillToAttach = em.getReference(billCollectionBillToAttach.getClass(), billCollectionBillToAttach.getIdBill());
                attachedBillCollection.add(billCollectionBillToAttach);
            }
            customer.setBillCollection(attachedBillCollection);
            em.persist(customer);
            for (Bill billCollectionBill : customer.getBillCollection()) {
                Customer oldCustomerIDOfBillCollectionBill = billCollectionBill.getCustomerID();
                billCollectionBill.setCustomerID(customer);
                billCollectionBill = em.merge(billCollectionBill);
                if (oldCustomerIDOfBillCollectionBill != null) {
                    oldCustomerIDOfBillCollectionBill.getBillCollection().remove(billCollectionBill);
                    oldCustomerIDOfBillCollectionBill = em.merge(oldCustomerIDOfBillCollectionBill);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findCustomer(customer.getIdCustomer()) != null) {
                throw new PreexistingEntityException("Customer " + customer + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Customer customer) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Customer persistentCustomer = em.find(Customer.class, customer.getIdCustomer());
            Collection<Bill> billCollectionOld = persistentCustomer.getBillCollection();
            Collection<Bill> billCollectionNew = customer.getBillCollection();
            Collection<Bill> attachedBillCollectionNew = new ArrayList<Bill>();
            for (Bill billCollectionNewBillToAttach : billCollectionNew) {
                billCollectionNewBillToAttach = em.getReference(billCollectionNewBillToAttach.getClass(), billCollectionNewBillToAttach.getIdBill());
                attachedBillCollectionNew.add(billCollectionNewBillToAttach);
            }
            billCollectionNew = attachedBillCollectionNew;
            customer.setBillCollection(billCollectionNew);
            customer = em.merge(customer);
            for (Bill billCollectionOldBill : billCollectionOld) {
                if (!billCollectionNew.contains(billCollectionOldBill)) {
                    billCollectionOldBill.setCustomerID(null);
                    billCollectionOldBill = em.merge(billCollectionOldBill);
                }
            }
            for (Bill billCollectionNewBill : billCollectionNew) {
                if (!billCollectionOld.contains(billCollectionNewBill)) {
                    Customer oldCustomerIDOfBillCollectionNewBill = billCollectionNewBill.getCustomerID();
                    billCollectionNewBill.setCustomerID(customer);
                    billCollectionNewBill = em.merge(billCollectionNewBill);
                    if (oldCustomerIDOfBillCollectionNewBill != null && !oldCustomerIDOfBillCollectionNewBill.equals(customer)) {
                        oldCustomerIDOfBillCollectionNewBill.getBillCollection().remove(billCollectionNewBill);
                        oldCustomerIDOfBillCollectionNewBill = em.merge(oldCustomerIDOfBillCollectionNewBill);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = customer.getIdCustomer();
                if (findCustomer(id) == null) {
                    throw new NonexistentEntityException("The customer with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Customer customer;
            try {
                customer = em.getReference(Customer.class, id);
                customer.getIdCustomer();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The customer with id " + id + " no longer exists.", enfe);
            }
            Collection<Bill> billCollection = customer.getBillCollection();
            for (Bill billCollectionBill : billCollection) {
                billCollectionBill.setCustomerID(null);
                billCollectionBill = em.merge(billCollectionBill);
            }
            em.remove(customer);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Customer> findCustomerEntities() {
        return findCustomerEntities(true, -1, -1);
    }

    public List<Customer> findCustomerEntities(int maxResults, int firstResult) {
        return findCustomerEntities(false, maxResults, firstResult);
    }

    private List<Customer> findCustomerEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Customer.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Customer findCustomer(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Customer.class, id);
        } finally {
            em.close();
        }
    }

    public int getCustomerCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Customer> rt = cq.from(Customer.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
